﻿//PortfolioComboBox.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Xaml
{
	using System.Collections.Generic;
	using System.Windows;
	using System.Windows.Controls;

	using Ecng.Xaml;

	using StockSharp.BusinessEntities;

	/// <summary>
	/// Комбо элемент для выбора портфеля.
	/// </summary>
	public class PortfolioComboBox : ComboBox
	{
		private readonly ThreadSafeObservableCollection<Portfolio> _visiblePortfolios = new ThreadSafeObservableCollection<Portfolio>();

		/// <summary>
		/// Создать <see cref="PortfolioComboBox"/>.
		/// </summary>
		public PortfolioComboBox()
		{
			DisplayMemberPath = "Name";
			ItemsSource = _visiblePortfolios;
		}

		private ITrader _trader;

		/// <summary>
		/// Шлюз к торговой системе.
		/// </summary>
		public ITrader Trader
		{
			get { return _trader; }
			set
			{
				if (_trader != value)
				{
					if (_trader != null)
					{
						_trader.NewPortfolios -= OnNewPortfolios;
						_visiblePortfolios.Clear();
					}

					_trader = value;

					if (_trader != null)
					{
						OnNewPortfolios(_trader.Portfolios);
						_trader.NewPortfolios += OnNewPortfolios;
					}
				}
			}
		}

		/// <summary>
		/// Доступные портфели.
		/// </summary>
		public IList<Portfolio> Portfolios
		{
			get { return _visiblePortfolios; }
		}

		private void OnNewPortfolios(IEnumerable<Portfolio> portfolios)
		{
			_visiblePortfolios.AddRange(portfolios);
		}

		/// <summary>
		/// <see cref="DependencyProperty"/> для <see cref="SelectedPortfolio"/>.
		/// </summary>
		public static readonly DependencyProperty SelectedPortfolioProperty =
			 DependencyProperty.Register("SelectedPortfolio", typeof(Portfolio), typeof(PortfolioComboBox),
				new FrameworkPropertyMetadata(null, OnSelectedPortfolioPropertyChanged));

		/// <summary>
		/// Выбранный портфель.
		/// </summary>
		public Portfolio SelectedPortfolio
		{
			get { return (Portfolio)GetValue(SelectedPortfolioProperty); }
			set { SetValue(SelectedPortfolioProperty, value); }
		}

		private static void OnSelectedPortfolioPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
		{
			var portfolio = (Portfolio)e.NewValue;
			var cb = (PortfolioComboBox)source;

			cb.SelectedItem = portfolio;
		}

		/// <summary>
		/// Обработчик события смены выбранного элемента.
		/// </summary>
		/// <param name="e">Параметр события.</param>
		protected override void OnSelectionChanged(SelectionChangedEventArgs e)
		{
			base.OnSelectionChanged(e);

			SelectedPortfolio = (Portfolio)SelectedItem;
		}
	}
}